<template>
  <div class="favorite-sellers-tab">
    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ favoriteSellers.length }}</div>
              <div class="stat-label">收藏卖家</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ latestFavoriteTime }}</div>
              <div class="stat-label">最近收藏</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ averageDays }}</div>
              <div class="stat-label">平均收藏天数</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-row :gutter="16" align="middle">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索卖家昵称"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="timeRange" placeholder="收藏时间" size="small" clearable>
            <el-option label="全部时间" value="" />
            <el-option label="最近7天" value="7" />
            <el-option label="最近30天" value="30" />
            <el-option label="最近90天" value="90" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="small" @click="exportSellers">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 卖家列表 -->
    <div class="sellers-section">
      <el-table 
        :data="filteredSellers" 
        border 
        stripe 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        row-class-name="seller-row"
      >
        <el-table-column prop="idx" label="序号" width="80" align="center" />
        
        <el-table-column label="卖家信息" min-width="200">
          <template #default="scope">
            <div class="seller-info">
              <div class="seller-avatar">
                <el-avatar :size="40" :src="getSellerAvatar(scope.row.nickname)">
                  {{ getInitials(scope.row.nickname) }}
                </el-avatar>
              </div>
              <div class="seller-details">
                <div class="seller-name">{{ scope.row.nickname }}</div>
                <div class="seller-id">ID: {{ scope.row.idx }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="联系方式" min-width="180">
          <template #default="scope">
            <div class="contact-info">
              <div class="contact-item">
                <el-icon><Phone /></el-icon>
                <span class="contact-text">{{ maskPhone(scope.row.contact) }}</span>
              </div>
              <div class="contact-actions">
                <el-button size="small" type="primary" text @click="copyContact(scope.row)">
                  <el-icon><CopyDocument /></el-icon>
                  复制
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="time" label="收藏时间" width="180">
          <template #default="scope">
            <div class="time-info">
              <div class="time-date">{{ formatDate(scope.row.time) }}</div>
              <div class="time-hour">{{ formatTime(scope.row.time) }}</div>
              <div class="time-ago">{{ getTimeAgo(scope.row.time) }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="primary" text @click="viewSellerDetail(scope.row)">
                查看详情
              </el-button>
              <el-button size="small" type="danger" text @click="removeFavorite(scope.row)">
                取消收藏
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredSellers.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, computed } from 'vue';
import { 
  User, 
  Clock, 
  TrendCharts, 
  Search, 
  Download, 
  Phone, 
  CopyDocument 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps<{ favoriteSellers: any[] }>();

// 响应式数据
const searchKeyword = ref('');
const timeRange = ref('');
const currentPage = ref(1);
const pageSize = ref(10);

// 计算属性
const latestFavoriteTime = computed(() => {
  if (props.favoriteSellers.length === 0) return '暂无';
  const latest = props.favoriteSellers.reduce((latest, current) => {
    return new Date(current.time) > new Date(latest.time) ? current : latest;
  });
  return formatDate(latest.time);
});

const averageDays = computed(() => {
  if (props.favoriteSellers.length === 0) return '0';
  const now = new Date();
  const totalDays = props.favoriteSellers.reduce((sum, seller) => {
    const favoriteDate = new Date(seller.time);
    const daysDiff = Math.floor((now.getTime() - favoriteDate.getTime()) / (1000 * 60 * 60 * 24));
    return sum + daysDiff;
  }, 0);
  return Math.round(totalDays / props.favoriteSellers.length);
});

const filteredSellers = computed(() => {
  let filtered = props.favoriteSellers;
  
  // 搜索过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(seller => 
      seller.nickname.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 时间范围过滤
  if (timeRange.value) {
    const days = parseInt(timeRange.value);
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);
    
    filtered = filtered.filter(seller => {
      const favoriteDate = new Date(seller.time);
      return favoriteDate >= cutoffDate;
    });
  }
  
  return filtered;
});

// 方法
function maskPhone(phone: string) {
  if (!phone) return '';
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

function getSellerAvatar(nickname: string) {
  // 这里可以根据昵称生成头像URL，暂时返回空
  return '';
}

function getInitials(nickname: string) {
  return nickname.substring(0, 2).toUpperCase();
}

function copyContact(seller: any) {
  navigator.clipboard.writeText(seller.contact).then(() => {
    ElMessage.success('联系方式已复制到剪贴板');
  }).catch(() => {
    ElMessage.error('复制失败');
  });
}

function formatDate(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
}

function formatTime(dateString: string) {
  const date = new Date(dateString);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
}

function getTimeAgo(dateString: string) {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffDays === 0) return '今天';
  if (diffDays === 1) return '昨天';
  if (diffDays < 7) return `${diffDays}天前`;
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`;
  if (diffDays < 365) return `${Math.floor(diffDays / 30)}个月前`;
  return `${Math.floor(diffDays / 365)}年前`;
}

function viewSellerDetail(seller: any) {
  ElMessage.info(`查看卖家详情: ${seller.nickname}`);
}

function removeFavorite(seller: any) {
  ElMessage.warning('取消收藏功能开发中...');
}

function exportSellers() {
  ElMessage.success('导出功能开发中...');
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;
}

function handleCurrentChange(page: number) {
  currentPage.value = page;
}
</script>

<style scoped>
.favorite-sellers-tab {
  padding: 20px;
}

/* 统计卡片样式 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 4px 12px rgba(240, 147, 251, 0.3);
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
}

.stat-icon {
  font-size: 24px;
  opacity: 0.9;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 卖家列表样式 */
.sellers-section {
  margin-bottom: 20px;
}

.seller-row:hover {
  background-color: #f0f9ff !important;
}

.seller-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.seller-avatar {
  flex-shrink: 0;
}

.seller-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.seller-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.seller-id {
  font-size: 11px;
  color: #909399;
}

.contact-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.contact-item .el-icon {
  color: #409eff;
  font-size: 14px;
}

.contact-text {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.contact-actions {
  display: flex;
  justify-content: flex-start;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-date {
  font-size: 12px;
  color: #606266;
}

.time-hour {
  font-size: 11px;
  color: #909399;
}

.time-ago {
  font-size: 10px;
  color: #c0c4cc;
  font-style: italic;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 16px;
  }
  
  .filter-section .el-col {
    margin-bottom: 12px;
  }
}
</style> 